﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using SimpleServiceBus.Messages.Management.Monitoring;

namespace SimpleServiceBus.EndpointMonitorService
{
    public partial class EndpointMonitorWinFormHost : Form
    {
        private EndpointMonitorServerHost serverHost;

        public EndpointMonitorWinFormHost()
        {
            InitializeComponent();
        }

        //protected override void OnLoad(EventArgs e)
        //{
        //    base.OnLoad(e);
        //    //StartServer();
        //}

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            StopServer();
        }

        private void btnStartStop_Click(object sender, EventArgs e)
        {
            if (serverHost == null || !serverHost.IsRunning)
                StartServer();
            else
            {
                StopServer();
            }
        }

        private void StartServer()
        {
            try
            {
                Output("Starting server...");
                if (serverHost == null)
                {
                    serverHost = new EndpointMonitorServerHost();
                    BindToEvents(serverHost);
                    
                }
                if (serverHost.IsRunning)
                    return;

                serverHost.Start();
                btnStartStop.Text = "Stop Server";
                Output("Server started.");
            }
            catch (Exception ex)
            {
                Output(ex.ToString());
                btnStartStop.Text = "##ERROR##";
                btnStartStop.Enabled = false;
            }

        }

        private void StopServer()
        {
            try
            {
                Output("Stopping server...");
                if (serverHost != null && serverHost.IsRunning)
                    serverHost.Stop();
                serverHost = null;
                btnStartStop.Text = "Start Server";
                Output("Server stopped.");
            }
            catch (Exception ex)
            {
                Output(ex.ToString());
                btnStartStop.Text = "##ERROR##";
                btnStartStop.Enabled = false;
            }
           
        }

        private void BindToEvents(EndpointMonitorServerHost serverHost)
        {
            serverHost.EndpointStatusExpired += (sender, args)
                        => Output(args.EndpointID + " offline @ " + args.LastStatusReceived);

            //Status updates are covered by the EndpointStatusSummaryUpdated event,
            //which we attach to below
            serverHost.EndpointStatusUpdated += (sender, args) =>
                {
                    if (
                        !(args.LastStatusMessage is EndpointStatusUpdateNotification))
                    {
                        Output(args.EndpointID + " updated @ " +
                               args.LastStatusReceived
                               + " (" + args.LastStatusMessage + ")");
                    }
                };

            serverHost.MessageProcessingError += (sender, args)
                => Output("Message processing error:" + args.Exception);

            serverHost.EndpointStatusSummaryUpdated += (sender, args)
               => Output("Endpoint summary broadcast @ " + DateTime.Now);
        }

        private void Output(string message)
        {
            if (InvokeRequired)
            {
                Action<string> del = Output;

                Invoke(del, message);
            }
            else
                txtOutput.Text += String.Format("{0}{1}", message, Environment.NewLine);
        }

        private void txtOutput_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
